package com.eques.util

import android.app.Dialog
import android.content.Context
import android.view.View
import android.widget.TextView
import com.eques.demo.R
import com.eques.view.MyProgressDialog
import org.apache.commons.lang3.StringUtils
import java.io.File
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale
import java.util.TimeZone

class EquesMytool {

    val APP_NAME = "Demo" //文件名常量,dingdong


    private var equesMytool: EquesMytool? = null

    private var mContext: Context? = null

    private var loadingDialog: Dialog? = null

    constructor(mContext: Context?) {
        this.mContext = mContext
    }

    fun getInstance(context: Context): EquesMytool? {
        if (equesMytool == null) {
            synchronized(EquesMytool::class.java) {
                if (equesMytool == null) {
                   equesMytool = EquesMytool(context)
                }
            }
        }
        return equesMytool
    }

    fun getDegree264(cameraId: Int): Int {
        return if (cameraId <= 0) {
            90
        } else if (cameraId == 4) {
            180
        } else if (cameraId == 3) {
            90
        } else if (cameraId == 5) {
            0
        } else {
            270
        }
    }

    fun md5(text: String): String? {
        var digest: MessageDigest? = null
        try {
            digest = MessageDigest.getInstance("MD5")
            digest.update(text.toByteArray())
        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
        }
        return if (digest != null) {
            cvtHex(digest.digest())
        } else {
            null
        }
    }

    fun cvtHex(bin: ByteArray): String {
        val stringBuf = StringBuffer(bin.size * 2)
        val len = bin.size
        for (i in 0 until len) {
            if (bin[i].toInt() and 0xff < 0x10) {
                stringBuf.append("0")
            }
            stringBuf.append(Integer.toHexString(bin[i].toInt() and 0xFF))
        }
        return stringBuf.toString()
    }

    fun createProgressDialog(ctx: Context?, msg: Int, showFlag: Boolean): Dialog? {
        if (loadingDialog == null) {
            loadingDialog = MyProgressDialog.createLoadingDialog(ctx)
            if (msg != Config.PROGRESS_ERROR_CODE) {
                val tv_loading: TextView = loadingDialog!!.findViewById<TextView>(R.id.tv_loading)
                tv_loading.setText(msg)
                if (!showFlag) {
                    tv_loading.visibility = View.GONE
                } else {
                    tv_loading.visibility = View.VISIBLE
                }
            }
            if (!loadingDialog!!.isShowing()) {
                loadingDialog!!.show()
            }
        }
        return loadingDialog
    }

    /**
     * 取消加载进度条
     */
    fun stopProgressDialog() {
        if (loadingDialog != null && loadingDialog!!.isShowing()) {
            loadingDialog!!.dismiss()
            loadingDialog = null
        }
    }


    /**
     * 获取夏令时是差值（分钟）
     *
     * @return
     */
    fun getTimeZoneDSTHour(): String? {
        var timeValueStr: String
        val calendar = Calendar.getInstance()
        val timeZone1 = calendar.timeZone
        val tz = TimeZone.getTimeZone(timeZone1.id)
        val data = calendar.timeInMillis
        val offset = tz.getOffset(data)
        // 毫秒转分钟
        val timeValue = offset / 60000 / 60
        val halfValue = offset / 60000 % 60
        timeValueStr = if (timeValue >= 0) {
            "+$timeValue"
        } else {
            "-" + -timeValue
        }
        if (halfValue > 0) {
            timeValueStr = "$timeValueStr:$halfValue"
        }
        return timeValueStr
    }

    /**
     * 本地抓拍路径
     *
     * @param ctx
     * @param name
     * @param folderName
     * @param userName
     * @return
     */
    fun captureLocalMp4Path(
        ctx: Context?,
        name: String,
        folderName: String,
        userName: String?
    ): String? {
        var rootPath: String = getCamPath(ctx, userName!!)
        if (!StringUtils.isBlank(name)) {
            rootPath = StringUtils.join(rootPath, name, File.separator, "mp4", File.separator)
        }
        if (!StringUtils.isBlank(folderName)) {
            rootPath = StringUtils.join(rootPath, folderName, File.separator)
        }
        return rootPath
    }


    fun getCamPath(ctx: Context?, userName: String): String {
        val rootPath = FileHelper.getRootFilePath(ctx)
        val camPicPath =
            rootPath + APP_NAME + File.separator + userName + File.separator
        FileHelper.createDirectory(camPicPath)
        return camPicPath
    }

    fun createCaptureFolderName(): String? {
        val cal = Calendar.getInstance()
        return format(cal.time, "yyyy-MM-dd")
    }

    fun format(date: Date?, format: String?): String? {
        val dateString: String
        val df: DateFormat = SimpleDateFormat(format, Locale.getDefault())
        dateString = try {
            df.format(date)
        } catch (e: Exception) {
            df.format(Date())
        }
        return dateString
    }

    /**
     * 根据id设置角度
     *
     * @param cameraId
     * @return
     */
    fun getDegree(cameraId: Int): Int {
        return if (cameraId <= 0) {
            90
        } else if (cameraId == 4) {
            180
        } else if (cameraId == 3) {
            90
        } else if (cameraId == 5) {
            0
        } else {
            -90
        }
    }

    open fun convertSecondsToTime(seconds: Int): String? {
        val hours = seconds / 3600
        val minutes = seconds % 3600 / 60
        val remainingSeconds = seconds % 60
        return String.format("%02d:%02d:%02d", hours, minutes, remainingSeconds)
    }

    /**
     *
     * 将二进制整数部分转换成十六进制
     *
     * @param integer 二进制整数部分字符串
     *
     * @return 转换后的十六进制字符串
     */
    fun binaryIntToHexadecimal(integer: String): String? {
        val integerSum = StringBuffer()
        var loop = 0 // 循环次数
        loop = if (integer.length % 4 == 0) {
            integer.length / 4
        } else {
            integer.length / 4 + 1
        }
        var binary = ""
        for (i in 1..loop) {
            binary = if (i != loop) {
                integer.substring(
                    integer.length - i * 4,
                    integer.length - i * 4 + 4
                )
            } else ({
                appendZero(
                    integer.substring(0, integer.length - (i - 1) * 4),
                    4, true
                )
            }).toString()
            integerSum.append(
               toHex(
                  binaryIntToDecimalism(binary).toString()
                )
            )
        }
        return integerSum.reverse().toString()
    }

    /**
     *
     * 将二进制整数部分转换成十进制
     *
     * @param inteter 二进制整数部分字符串
     *
     * @return 转换后的十进制数值
     */
    fun binaryIntToDecimalism(inteter: String): Int {
        var inteterSum = 0
        for (i in inteter.length downTo 1) {
            var scale = 2
            if (inteter[-(i - inteter.length)] == '1') {
                if (i != 1) {
                    for (j in 1 until i - 1) {
                        scale *= 2
                    }
                } else {
                    scale = 1
                }
            } else {
                scale = 0
            }
            inteterSum += scale
        }
        return inteterSum
    }

    fun toHexString(number: Int): String? {
        val hexResult = Integer.toHexString(number)
        return if (hexResult.length == 1) {
            "0$hexResult"
        } else hexResult
    }

    /**
     *
     * 将10~15转换成A~F
     *
     *
     * @return 转换后的十六进制数值
     */
    fun toHex(hex: String): String? {
        var str = ""
        str = when (hex.toInt()) {
            10 -> "A"
            11 -> "B"
            12 -> "C"
            13 -> "D"
            14 -> "E"
            15 -> "F"
            else -> hex
        }
        return str
    }

    /**
     *
     * 根据补位标志将源字符串补位到指定长度
     *
     * @param str 源字符串
     *
     * @param len 补位到指定长度
     *
     * @param flag 补位标志 true-左补;false-右补
     *
     * @return 补位后的字符串
     */
    fun appendZero(str: String?, len: Int, flag: Boolean): String? {
        var str = str
        val zero = "0"
        if (null == str || str.length == 0) {
            return ""
        }
        if (str.length >= len) {
            return str
        }
        for (i in str!!.length until len) {
            if (flag) {
                str = zero + str
            } else {
                str += zero
            }
        }
        return str
    }


    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    fun parseHexStr2Byte(hex: String): String? {
        if (StringUtils.isEmpty(hex) || hex.length % 2 != 0) {
            return ""
        }
        val binaryString = StringBuilder()
        var tmp: String
        for (i in 0 until hex.length) {
            tmp = "0000" + Integer.toBinaryString(hex.substring(i, i + 1).toInt(16))
            binaryString.append(tmp.substring(tmp.length - 4))
        }
        return binaryString.toString()
    }

    /**
     * 获取时分
     *
     * @return
     */
    fun getHD(timeMillis: Long): String? {
        val d = Date(timeMillis)
        val sdf = SimpleDateFormat("HH:mm")
        return sdf.format(d)
    }

    /**
     * 获取年月日
     *
     * @return
     */
    fun getYMD(timeMillis: Long): String? {
        val d = Date(timeMillis)
        val sdf = SimpleDateFormat("yyyy.MM.dd")
        return sdf.format(d)
    }
}